package com.wang.jmonkey.ca.handler.code;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.wang.jmonkey.ca.model.ValidateCode;
import com.wang.jmonkey.common.constant.SecurityConstant;
import com.wang.jmonkey.common.constant.ValidateConstant;
import com.wang.jmonkey.redis.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Description 图形验证码处理器
 * @Author HeJiawang
 * @Date 2021/5/12 17:01
 */
@Component
public class ImageValidateCodeHandler extends AbstractValidateCodeHandler {

    @Autowired
    @Qualifier("redisUtil")
    private RedisUtil redisUtil;

    @Override
    public void save(ValidateCode validateCode) {
        if (StrUtil.isEmpty(validateCode.getCode())) return;

        String deviceId = UUID.randomUUID().toString().replaceAll("-", "");
        validateCode.setDeviceId(deviceId);

        redisUtil.set(deviceId, validateCode.getCode(), ValidateConstant.ExpireIn.ImageCode.getKey());
    }

    @Override
    public void send(ValidateCode validateCode, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        response.addHeader("Pragma", "No-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Access-Control-Expose-Headers", "Origin, Content-Type, Accept, Authorization, x-requested-with, cache-control,Access-Control-Allow-Origin,Access-Control-Allow-Credentials,uuid");
    }

    @Override
    public boolean validate(HttpServletRequest request) {
        String deviceId = StrUtil.toString(request.getAttribute(SecurityConstant.LoginParameter.deviceId.getKey()));
        String rawCode = ObjectUtil.isNotEmpty(redisUtil.get(deviceId)) ?
                StrUtil.toString(redisUtil.get(deviceId)) : StrUtil.EMPTY;
        redisUtil.del(deviceId);    // 不管验证码是否输入正确，只能使用一次，

        String code = StrUtil.toString(request.getAttribute(SecurityConstant.LoginParameter.code.getKey()));

        if (StrUtil.isEmpty(rawCode) || StrUtil.isEmpty(code) || !StrUtil.equalsAnyIgnoreCase(rawCode, code)) {
            return false;
        }

        return true;
    }
}
